<?php
namespace SmartDevice\Model;

use Zend\Db\TableGateway\TableGateway;

class OwnerTable
{
	protected $tableGateway;

	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
	}

	public function fetchAll()
	{
		$resultSet = $this->tableGateway->select();
		return $resultSet;
	}

// 	public function getOwner($ownerId)
// 	{
// 		$id  = (int) $ownerId;
// 		$rowset = $this->tableGateway->select(array('owner_id' => $ownerId));
// 		$row = $rowset->current();
// 		if (!$row) {
// 			throw new \Exception("Could not find row $owner_id");
// 		}
// 		return $row;
// 	}

	public function saveOwner(Owner $owner)
	{
		$data = array(
				'owner_id' => $owner->ownerId,
				'email'  => $owner->email,
				'phoneno'  => $owner->phoneNo,
				'auth_token'  => $owner->authToken,
				'created_at'  => $owner->createdAt,
				'updated_at'  => $owner->updatedAt,
		);

		$owner_id = (int)$owner->ownerId;
		if ($owner_id == 0) {
			$this->tableGateway->insert($data);
		} else {
			if ($this->getOwner($owner_id)) {
				$this->tableGateway->update($data, array('owner_id' => $owner_id));
			} else {
				throw new \Exception('Form id does not exist');
			}
		}
	}
	
	public function getOwner($ownerId)
	{
		$id  = (int) $ownerId;
		$rowset = $this->tableGateway->select(array('id' => $ownerId));
		$row = $rowset->current();
		if (!$row) {
			throw new \Exception("Could not find row $id");
		}
		return $row;
	}

	public function deleteOwner($id)
	{
		$this->tableGateway->delete(array('id' => $id));
	}
}